import { createRouter, createWebHistory } from 'vue-router'
import { afterEach, beforeEach } from './scrollBehavior'
import { notification } from 'ant-design-vue'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import tool from '@/utils/tool'
import { cloneDeep } from "lodash-es";

// 进度条配置
NProgress.configure({ showSpinner: false, speed: 500 })

// 路由
const routes = [
  {
    name: 'layout',
    path: '/',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        name: "index",
        path: "index",
        component: () => import('@/views/index.vue')
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // const token = tool.data.get('TOKEN')
  // if (to.path === '/login') {
  //   // 当用户输入了login路由，将其跳转首页即可
  //   if (token) {
  //     next({
  //       path: '/'
  //     })
  //     return false
  //   }
  //   // 删除路由(替换当前layout路由)
  //   router.addRoute(routes[0])
  //   next()
  //   return false
  // } else {
  //   // 这里需要使用 localStorage 保存登录之前要访问的页面
  //   tool.data.set('LAST_VIEWS_PATH', to.fullPath)
  // }
  //
  // if (!token) {
  //   next({
  //     path: '/login'
  //   })
  //   return false
  // }
  beforeEach(to, from)
  next()
});

router.afterEach((to, from) => {
  afterEach(to, from)
  NProgress.done()
})

router.onError((error) => {
  NProgress.done()
  notification.error({
    message: '路由错误',
    description: error.message
  })
})

const userRoutes = {
  // 默认模块，仅限于后端未添加任何单页配置，用此路由
  module: [
    {
      id: '01',
      name: 'homeModule',
      path: '/homeModule',
      component: '',
      meta: {
        title: '默认',
        type: 'module',
        icon: 'bank-outlined'
      },
      children: []
    }
  ],
  // 默认首页、个人中心
  menu: [
    {
      id: '001',
      name: 'index',
      path: '/index',
      component: 'index/index',
      meta: {
        title: '首页',
        type: 'menu',
        icon: 'bank-outlined',
        affix: true
      },
      children: []
    },
    {
      id: '002',
      name: 'userCenter',
      path: '/userCenter',
      component: 'sys/user/userCenter',
      meta: {
        title: '个人中心',
        type: 'menu',
        hidden: true
      },
      children: []
    }
  ]
}

// 入侵追加自定义方法，对象
router.getMenu = () => {
  let apiMenu = tool.data.get('MENU') || []
  // 增加固定路由
  if (apiMenu.length === 0) {
    // 创建默认模块，显示默认菜单
    apiMenu[0] = cloneDeep(userRoutes.module[0])
    const userMenu = userRoutes.menu
    const childrenApiMenu = apiMenu[0].children
    apiMenu[0].children = [...userMenu, ...childrenApiMenu]
  }
  return apiMenu
}

export default router
